from Crypto.Cipher import AES
import base64
import os
import gdata.docs.service
import sys
import rsa



BLOCK_SIZE = 32
PADDING = '{'



def aes_decrypt( secret, content) :
	# one-liner to sufficiently pad the text to be encrypted
	pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

	# one-liners to encrypt/encode and decrypt/decode a string
	# encrypt with AES, encode with base64
	DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
	
	# create a cipher object using the random secret
	cipher = AES.new(secret)
	
	# encode a string
	return DecodeAES(cipher, content)


print 'Title of the file to download'
file_title = sys.stdin.readline().rstrip()

print 'Destination file path:'
file_path = sys.stdin.readline().rstrip()

# Create a client class which will make HTTP requests with Google Docs server.
client = gdata.docs.service.DocsService()
# Authenticate using your Google Docs email address and password.
print 'User name :'
user_name = sys.stdin.readline().rstrip()
print 'Password :'
password = sys.stdin.readline().rstrip()

client.ClientLogin(user_name, password)

def FindEntry(feed, name):
  if not feed.entry:
    print 'No files available'
  for entry in feed.entry:
	if(entry.title.text.encode('UTF-8') == name) :
		return entry

  print 'Not found'
  return None
feed = client.GetDocumentListFeed()
entry = FindEntry(feed, file_title)
if entry is not None :
	client.Export(entry,file_path)
	decryptedFile = file_path + '_decrypted'
	f = open(file_path, 'r')
	content = ''
	isContent = False
	encryptedKey = ''
	isKey = False
	keyStart = 'EncryptedKeys:START'
	keyEnd = 'EncryptedKeys:END'
	contentStart = 'Content:START'
	contentEnd = 'Content:END'
	for line in f:
		if line.find(keyStart) != -1 :
			isKey = True
			continue
		if line.find(keyEnd) != -1 :
			isKey = False
			continue

		if isKey == True :
			encryptedKey += line

		if line.find(contentStart) != -1 :
			isContent = True
			continue
		if line.find(contentEnd) != -1 :
			isContent = False
			continue

		if isContent == True :
			content += line

	home = os.getenv("HOME")
	fpri = open(home + '/.gd_priv', 'r')
	pri = eval(fpri.read())
	
	
	end_index = encryptedKey.index(', pub : ')
	encryptedKey = encryptedKey[4:end_index]
	
	aes_key = rsa.decrypt(encryptedKey, pri)
	pt = aes_decrypt(aes_key, content)
	fout = open(decryptedFile, 'w')
	fout.write(pt)
	fout.close()
